import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ChartEChartsOption } from '@delon/chart/chart-echarts';
import { _HttpClient, SettingsService } from '@delon/theme';
import * as moment from 'moment';
import { NzCascaderOption } from 'ng-zorro-antd/cascader';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { zip } from 'rxjs';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-business-shop',
  templateUrl: './shop.component.html',
  styleUrls: ['./shop.component.less']
})
export class BusinessShopComponent implements OnInit {
  loading = true;
  url = `api/shop/trend`;
  isAdmin = false;
  q: {
    shopId: number;
    dateType: number;
    dateVal: string;
  } = {
    shopId: 0,
    dateType: 1,
    dateVal: moment().subtract(1, 'days').format('YYYY-MM-DD')
  };
  statistics_date = this.q.dateVal;
  compareText = '较前一日';

  option: ChartEChartsOption | undefined;
  firstOption: ChartEChartsOption | undefined;
  shops = [];
  shopMap = {};
  totalData: any;
  secondData = [];

  constructor(private http: _HttpClient, private cdr: ChangeDetectorRef, private settingService: SettingsService) {
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
    }
    this.loadShops();
  }

  ngOnInit = (): void => {};

  loadShops(): void {
    //let uri = `api/shop_map`;
    let uri = `api/shop_map_full`;
    this.http.get(uri).subscribe(res => {
      this.genCompanyShopOptions(res.data['companies'], res.data['shops']);
      // @ts-ignore
      this.q.shopId = this.values[1];
      this.loadDataFromServer();
    });
  }

  loadDataFromServer(): void {
    this.loading = true;
    if (this.q.shopId > 0) {
      zip(
        this.http.get(`api/shop/trend`, this.q),
        this.http.get(`api/shop/first_traffic_trend`, this.q),
        this.http.get(`api/shop/second_traffic_rank`, this.q)
      )
        .pipe(
          finalize(() => {
            this.loading = false;
          })
        )
        .subscribe(([trend, first, second]: [NzSafeAny, NzSafeAny, NzSafeAny]) => {
          let [firstData, secondData] = [first.data, second.data];
          this.totalData = trend.data.total;
          // 处理折线图
          let [dateAxis, y1, y2, y3, y4, y5, y6, y7, y8] = [[], [], [], [], [], [], [], [], []];
          if (trend.data.list) {
            for (let i = 0; i < trend.data.list.length; i++) {
              let itemData = trend.data.list[i];
              // @ts-ignore
              dateAxis.unshift(moment(itemData['date']).format('YYYY-MM-DD'));
              // @ts-ignore
              y1.unshift(itemData['ctm_item_view_pv']);
              // @ts-ignore
              y2.unshift(itemData['ctm_item_view_uv']);
              // @ts-ignore
              y3.unshift(itemData['per_customer_value']);
              // @ts-ignore
              y4.unshift(itemData['ctm_item_view_item_cnt']);
              // @ts-ignore
              y5.unshift(itemData['order_buyer_cnt']);
              // @ts-ignore
              y6.unshift(itemData['item_verified_uv']);
              // @ts-ignore
              y7.unshift((itemData['ctm_order_view_rate'] * 100).toFixed(2));
              // @ts-ignore
              y8.unshift((itemData['overtime_rate'] * 100).toFixed(2));
            }
          }
          this.option = {
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              type: 'category',
              data: dateAxis
            },
            yAxis: [
              {
                type: 'value',
                name: '数值',
                min: 0,
                interval: 1000
              },
              {
                type: 'value',
                name: '百分比',
                min: 0,
                interval: 0.1,
                axisLabel: {
                  formatter: '{value} %'
                }
              }
            ],
            legend: {
              data: ['商品浏览量', '商品访客数', '客单价', '被访问商品数', '下单买家数', '订单确认件数', '下单转化率', '超时罚金比']
            },
            series: [
              {
                name: '商品浏览量',
                data: y1,
                type: 'line',
                smooth: true,
                yAxisIndex: 0
              },
              {
                name: '商品访客数',
                data: y2,
                type: 'line',
                smooth: true,
                yAxisIndex: 0
              },
              {
                name: '客单价',
                data: y3,
                type: 'line',
                smooth: true,
                yAxisIndex: 0
              },
              {
                name: '被访问商品数',
                data: y4,
                type: 'line',
                smooth: true,
                yAxisIndex: 0
              },
              {
                name: '下单买家数',
                data: y5,
                type: 'line',
                smooth: true,
                yAxisIndex: 0
              },
              {
                name: '订单确认件数',
                data: y6,
                type: 'line',
                smooth: true,
                yAxisIndex: 0
              },
              {
                name: '下单转化率',
                data: y7,
                type: 'line',
                smooth: true,
                yAxisIndex: 1
              },
              {
                name: '超时罚金比',
                data: y8,
                type: 'line',
                smooth: true,
                yAxisIndex: 1
              }
            ]
          };
          // 处理一级流量排行
          if (firstData) {
            let fXAxis = [];
            let fs = [];
            let fKeys = Object.keys(firstData);
            let fLegend = [];
            for (let i in fKeys) {
              let key = fKeys[i];
              fLegend.unshift(key);
              let fVal = firstData[key];
              let fsv = {
                name: key,
                data: [],
                type: 'line',
                smooth: true,
                areaStyle: {}
              };
              for (let j = 0; j < fVal.length; j++) {
                // @ts-ignore
                if (i == 0) {
                  // @ts-ignore
                  fXAxis.push(fVal[j]['_id']['date']);
                }
                // @ts-ignore
                fsv.data.push(fVal[j]['val']);
              }
              fs.unshift(fsv);
            }
            this.firstOption = {
              tooltip: {
                trigger: 'axis'
              },
              xAxis: {
                type: 'category',
                data: fXAxis
              },
              yAxis: {},
              legend: {
                data: fLegend
              },
              series: fs
            };
          }
          this.secondData = secondData;
          this.cdr.markForCheck();
        });
    }
    this.cdr.detectChanges();
  }

  dateTypeChange(value: number) {
    this.q.dateVal = '';
    let yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD');
    if (value == 1) {
      this.statistics_date = yesterday;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer();
      this.compareText = '较前一日';
    } else if (value == 2) {
      this.statistics_date = `${moment().subtract(7, 'days').format('YYYY-MM-DD')}~${yesterday}`;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer();
      this.compareText = '较前7日';
    } else if (value == 3) {
      this.statistics_date = `${moment().subtract(30, 'days').format('YYYY-MM-DD')}~${yesterday}`;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer();
      this.compareText = '较前30日';
    } else if (value == 5) {
      this.compareText = '较前一月';
    } else if (value == 4) {
      this.compareText = '较前一日';
    }
    // chart.forceFit();
  }

  datePickerChange(value: any) {
    if (this.q.dateType == 4) {
      this.q.dateVal = moment(value).format('yyyy-MM-DD');
    } else if (this.q.dateType == 5) {
      this.q.dateVal = moment(value).format('yyyy-MM');
    }
    this.statistics_date = this.q.dateVal;
    this.loadDataFromServer();
  }

  companyShopOptions: NzCascaderOption[] | null = [];
  values: any[] | null = null;

  genCompanyShopOptions(companies: any[], shops: any[]): void {
    let companyList: NzCascaderOption[] = [];
    companies.forEach((company: { ID: number; company_name: string }) => {
      let companyShopItem: NzCascaderOption = {
        value: company.ID,
        label: this.isAdmin ? company.company_name : '***',
        companyId: company.ID,
        isLeaf: false,
        children: [],
        disabled: true
      };
      companyList.push(companyShopItem);
    });
    companyList.forEach(company => {
      shops.forEach((shop: { shop_id: number; company_id: number; fordeal_shop_name: string }) => {
        if (shop.company_id == company.value) {
          let companyShopItem: NzCascaderOption = {
            value: shop.shop_id,
            label: shop.fordeal_shop_name,
            companyId: company.value,
            isLeaf: true,
            disabled: false
          };
          company.disabled = false;
          // @ts-ignore
          company.children.push(companyShopItem);
        }
      });
    });
    // @ts-ignore
    this.values = [companyList[0].value, companyList[0].children[0].value];
    this.companyShopOptions = companyList;
    console.log(this.values);
    console.log(this.companyShopOptions);
  }

  onChanges(values: any) {
    this.q.shopId = values[1];
    this.loadDataFromServer();
  }
}
